package flst.ipiweb.persistance.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.List;

import flst.ipiweb.persistance.interfaces.IModeDeLivraisonDAL;
import flst.ipiweb.transverse.IPIWebException;
import flst.ipiweb.transverse.ModeDeLivraison;

public class ModeDeLivraisonJdbcDAL implements IModeDeLivraisonDAL{


	public void UpdateModeDeLivraison(ModeDeLivraison mdl) throws IPIWebException {
		
		Connection maconnection;

		try {
			maconnection = JdbcUtils.getInstance().getConnection();
			PreparedStatement req = maconnection.prepareStatement("UPDATE MODEDELIVRAISON SET COUTCLIENT = ?, COUTSUPERCLIENT = ? WHERE IDMODEDELIVRAISON =?;");
			
			req.setDouble(1, mdl.getCoutClient());
			req.setDouble(2, mdl.getCoutSuperClient());
			req.setInt(3, mdl.getId());
			req.execute();


			req.close();
			maconnection.close();
		} catch (Exception e) {
			throw new IPIWebException(e.getMessage());
		}
		
	}


	public List<ModeDeLivraison> getAllModeDeLivraison() throws IPIWebException {

		List<ModeDeLivraison> lmdl = new ArrayList<ModeDeLivraison>();
		Connection maconnection;

		try {
			maconnection = JdbcUtils.getInstance().getConnection();
			Statement req = maconnection.createStatement();
			String requeteselect = "SELECT LIBELLE, COUTCLIENT, COUTSUPERCLIENT, IDMODEDELIVRAISON FROM MODEDELIVRAISON ";
			req.execute(requeteselect);

			ResultSet rs = req.getResultSet();
			while (rs.next()) {
				
					ModeDeLivraison mdl = new ModeDeLivraison();
					mdl.setLibelle(rs.getString(1));
					mdl.setCoutClient(rs.getDouble(2));
					mdl.setCoutSuperClient(rs.getDouble(3));
					mdl.setId(rs.getInt(4));
					lmdl.add(mdl);
				
			}

			req.close();
			maconnection.close();
		} catch (Exception e) {
			throw new IPIWebException(e.getMessage());
		}
		return lmdl;
	}


	
	public ModeDeLivraison getModeDeLivraisonById(int id) throws IPIWebException {
		
		Connection maconnection;
		ModeDeLivraison mdl = new ModeDeLivraison();
		
		try {
			maconnection = JdbcUtils.getInstance().getConnection();
			PreparedStatement req = maconnection.prepareStatement("SELECT LIBELLE, COUTCLIENT, COUTSUPERCLIENT, IDMODEDELIVRAISON FROM MODEDELIVRAISON WHERE IDMODEDELIVRAISON = ? ;");
			req.setInt(1, id);
			req.execute();

			ResultSet rs = req.getResultSet();
			while (rs.next()) {
				mdl.setLibelle(rs.getString(1));
				mdl.setCoutClient(rs.getInt(2));
				mdl.setCoutSuperClient(rs.getInt(3));
				mdl.setId(id);
			}

			req.close();
			maconnection.close();
		} 
		catch (Exception e) {
			throw new IPIWebException(e.getMessage());
		}
		return mdl;
	}

}
